﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using IOP.SgrA.Input;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace VkSample41
{
    public class RotateSystem : ComponentSystem
    {

        private float angle;
        private float x;
        private float y;
        private float width;
        private float height;
        private IRenderGroup RenderGroup;
        private Camera Camera;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="contextManager"></param>
        public RotateSystem()
        {
        }

        public override void Initialization()
        {
            RenderGroup = Owner.RenderGroup;
            Camera = RenderGroup.Camera;
            width = Camera.Viewport.Width;
            height = Camera.Viewport.Height;
            RenderGroup.SetViewPort(0, 0, width / 2, height / 2, 0, 1);
        }

        /// <summary>
        /// 更新
        /// </summary>
        public override void Update(TimeSpan timeSpan)
        {
            angle++;
            if (angle >= 360.0) angle = 0;
            var state = Input.GetMouseButtonState(MouseButton.ButtonLeft);
            if(state.Action == InputAction.Click)
            {
                Vector2 vector = Input.GetMousePosition();
                x = vector.X;
                y = vector.Y;
                if (x > width / 4 * 3) x = (int)(width / 4 * 3);
                if (x < width / 4) x = (int)(width / 4);
                if (y > height / 4 * 3) y = (int)(height / 4 * 3);
                if (y < height / 4) y = (int)(height / 4);
                RenderGroup.SetViewPort(x - width / 4, y - height / 4, width / 2, height / 2, 0, 1);
            }
            ContextManager.Foreach<Group>((group) =>
            {
                Context local = ContextManager.GetContext(group.Entity);
                ref MVPMatrix mvp = ref local.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateRotationX(angle / 180.0f * MathF.PI);
                local.PushToRenderGroup();
            });
        }
    }

    public struct Group
    {
        public Entity Entity;
    }
}
